package com.eagle.scali.contentcenter.configuration;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;

/**
 * 根据Nacos服务端配置的权重，来制定ribbon的负债均衡策略（如将某个服务权重重置为0）
 * 参考
 * http://www.imooc.com/article/288660
 *
 * 如user-center 的v1调用content-center的v1
 * user-center 的v2调用content-center的v2
 * 则可以参考基于元数据的例子
 * http://www.imooc.com/article/288674
 */
@Slf4j
public class NacosWeightedRule extends AbstractLoadBalancerRule {
	@Autowired
	private NacosDiscoveryProperties nacosDiscoveryProperties;

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {

	}

	@Override
	public Server choose(Object key) {
		BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
		String name = loadBalancer.getName();
		//服务发现的响应api
		NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();

		//基于Nacos权重的负债均衡算法，selectOneHealthyInstance是Nacos内置的方法
		//自动算出权重
		try {
			Instance instance = namingService.selectOneHealthyInstance(name);
			log.info("instance ip= {}, instance port= {}", instance.getIp(), instance.getPort());
			return new NacosServer(instance);
		} catch (NacosException e) {
			e.printStackTrace();
		}
		return null;
	}
}
